<template>
  <dt-modal-edit ref="editRef" title="变更项目信息" @ok="onOk" @cancelData="cancelData" style="top: 20px">
    <div class="allBox">
      <div class="topBox">
        <span>
          <Icon style="vertical-align: -8px" size="30" color="#2D61F4" type="ios-list-box-outline" />
          {{ editInfo.tenantNameLast }}（编号：{{ editInfo.tenantCode }}）- {{ editInfo.tenantStatusName }}
        </span>
      </div>
      <div class="selBox">
        <Select v-model="editInfo.type" @on-change="changeName">
          <Option v-for="item in infoChangeList" :value="item.key" :key="item.key">{{ item.name }}</Option>
        </Select>
      </div>
      <div>
        <dt-info :label-width="130" ref="proInfo"></dt-info>
      </div>
      <Modal v-model="showModal" title="验证手机号" width="30%" @on-ok="checkOk" class="audio-modal">
        <p>
          该手机号为已注册手机号， 注册人员：沈立宇(SR001)。
          <br />
          <span style="color: #2d8cf0; cursor: pointer" @click="zpeople">查看人员所属组织</span>
          请确认，是否以该人员作为项目归属人？
        </p>
      </Modal>
    </div>
  </dt-modal-edit>
</template>

<script setup>
  import { ref, nextTick } from 'vue'
  import dt from '@dt/dt'
  import { editOpt, editOpt1 } from '../biz/proInfo'
  import apiMgr from '../biz/index.js'
  import moment from 'moment'
  import { useRouter } from 'vue-router'
  const [proInfo] = [ref()]
  const editInfo = ref({
    tenantName: '',
    companyId: '',
    companyName: '',
    belongUserPhone: null,
    phoneVerify: null,
    belongUserName: '',
    peopleCity: [],
    cityName: '',
    cityCode: '',
    provinceCode: '',
    effectEndDate: null,
    effectStartDate: null,
    day: '',
    accountNumber: '',
    changeDescription: '',
    effectDay: '',
    effectSurplusDay: '',

    freezeStartDate: '',
    freezeEndDate: '',
    freezeDay: '',
    freezeEndDateAddEffectSurplusDay: '',
    freeTips: ''
  })
  const emits = defineEmits(['successful'])
  const fun = {
    freeTips() {
      return editInfo.value.freeTips ? true : false
    },
    getFreezeStartDate: () => {
      return editInfo.value.freezeStartDate ? true : false
    },
    chooseCompanyName: (val) => {
      editInfo.value.companyName = val.label
    },
    getTenantStatus: () => {
      return editInfo.value.tenantStatus
    },
    getNum: () => {
      return editInfo.value.type
    },
    chooseCity: (val) => {
      if (val && val.length) {
        editInfo.value.cityName = `${val[0].cityName}-${val[1].cityName}`
      }
    },
    dataChange: (val) => {
      if (editInfo.value.effectEndDate && editInfo.value.effectStartDate) {
        let flag =
          new Date(editInfo.value.effectEndDate).getTime() <
          new Date(editInfo.value.effectStartDate).getTime()
        if (flag) {
          nextTick(() => {
            editInfo.value.effectEndDate = ''
            dt.ui.Message.warning('结束时间不能小于开始时间')
          })
        }

        // 变更日期有问题
        const startDate = moment(editInfo.value.effectStartDate, 'YYYY-MM-DD')
        const endDate = moment(editInfo.value.effectEndDate, 'YYYY-MM-DD')
        const currentDate = moment()
        const dayDiff = endDate.diff(startDate, 'days') + 1
        let surplusDayDiff = null
        editInfo.value.effectDay = dayDiff
        if (currentDate.isAfter(startDate)) {
          surplusDayDiff = Math.ceil(endDate.diff(currentDate, 'days', true)) + 1
        } else {
          surplusDayDiff = Math.ceil(endDate.diff(startDate, 'days', true)) + 1
        }
        editInfo.value.effectSurplusDay = surplusDayDiff
      }
    },
    dataFreeChange: (val) => {
      console.log(val, 'vvvv')
      if (editInfo.value.freezeStartDate && !editInfo.value.freezeEndDate) {
        editInfo.value.freezeDay = '永久'
        editInfo.value.freeTips = '设置说明：如“冻结结束日期”未填写，则表示该项目永久冻结'
      }
      if (editInfo.value.freezeEndDate && editInfo.value.freezeStartDate) {
        let flag =
          new Date(editInfo.value.freezeEndDate).getTime() <
          new Date(editInfo.value.freezeStartDate).getTime()
        if (flag) {
          nextTick(() => {
            editInfo.value.effectEndDate = ''
            dt.ui.Message.warning('结束时间不能小于开始时间')
          })
        } else {
          const startDate = moment(editInfo.value.freezeStartDate, 'YYYY-MM-DD')
          const endDate = moment(editInfo.value.freezeEndDate, 'YYYY-MM-DD')
          const dayDiff = endDate.diff(startDate, 'days') + 1
          editInfo.value.freezeDay = dayDiff
          let newMoment = endDate.add(editInfo.value.effectSurplusDayLast, 'days')
          editInfo.value.freezeEndDateAddEffectSurplusDay = newMoment.format('YYYY-MM-DD')
          editInfo.value.freeTips = `该项目将冻结至${editInfo.value.freezeEndDate}，并于${editInfo.value.freezeEndDateAddEffectSurplusDay}起恢复`
        }
      }
    }
  }
  const changeName = (val) => {
    if (val == 8 && (editInfo.value.tenantStatus == 2 || editInfo.value.tenantStatus == 4)) {
      let tips =
        editInfo.value.tenantStatus == 2
          ? '该项目暂未生效，不可变更“有效期”'
          : '该项目已失效，不可变更“有效期”'
      dt.ui.Modal.info({
        title: '注意',
        okText: '知道了',
        content: tips,
        onOk: () => {
          hide()
        }
      })
      proInfo.value.init(new editOpt1(fun), {})
      editInfo.value.type = ''
      return false
    } else {
      proInfo.value.init(new editOpt(fun), editInfo.value)
    }
  }
  function checkOk() {
    editInfo.value.phoneVerify = editInfo.value.belongUserPhone
  }
  const editRef = ref()

  const onOk = () => {
    if (!editInfo.value.type) {
      dt.ui.Message.warning('请选择变更项')
      return false
    }

    proInfo.value.validate().then(async (res) => {
      if (res) {
        let tipVal = null
        if (editInfo.value.type == 2) {
          tipVal = `请确认，是否将项目名称从“${editInfo.value.tenantNameLast}”变更为“${editInfo.value.tenantName}”？`
        } else if (editInfo.value.type == 3) {
          if (editInfo.value.companyId == -1) {
            tipVal = `请确认，是否取消合同主体“${editInfo.value.companyNameLast}”与项目的关联？`
          } else {
            tipVal = `请确认，是否将项目合同主体从“${editInfo.value.companyNameLast || '-'}”变更为“${
              editInfo.value.companyName
            }”？`
          }
        } else if (editInfo.value.type == 4) {
          tipVal = `请确认，是否将项目所属人名称从“${editInfo.value.belongUserNameLast}”变更为“${editInfo.value.belongUserName}”？`
        } else if (editInfo.value.type == 5) {
          let params = {
            phone: editInfo.value.belongUserPhone
          }
          tipVal = await new Promise((resolve, reject) => {
            apiMgr
              .getTenantInfoByPhoneForWeb(params)
              .then((res) => {
                if (res.registerStatus) {
                  dt.ui.Modal.info({
                    title: '已注册',
                    okText: '知道了',
                    content: `该手机号已被其他人员注册`,
                    onOk: () => {
                      resolve(false)
                    }
                  })
                } else {
                  console.log('ddddddddd')
                  resolve(
                    `请确认，是否将所属人“${editInfo.value.belongUserNameLast}”的手机号从“${editInfo.value.belongUserPhoneLast}”变更为“${editInfo.value.belongUserPhone}”`
                  )
                }
              })
              .catch(reject)
          })
          // await apiMgr.getTenantInfoByPhoneForWeb(params).then((res) => {
          //   if (res.registerStatus) {
          //     dt.ui.Modal.info({
          //       title: '已注册',
          //       okText: '知道了',
          //       content: `该手机号已被其他人员注册`,
          //       onOk: () => {
          //         return false
          //       }
          //     })
          //   } else {
          //     console.log('ddddddddd')
          //     tipVal = `请确认，是否将所属人“${editInfo.value.belongUserNameLast}”的手机号从“${editInfo.value.belongUserPhoneLast}”变更为“${editInfo.value.belongUserPhone}”`
          //   }
          // })
        } else if (editInfo.value.type == 6) {
          tipVal = `请确认，是否将项目所属城市从“${editInfo.value.cityLast}”变更为“${editInfo.value.cityName}”`
        } else if (editInfo.value.type == 7) {
          tipVal = `请确认，是否将项目有效期从“${editInfo.value.effectStartDateLast} 至 ${
            editInfo.value.effectEndDateLast
          }”变更为“${editInfo.value.effectStartDate} 至 ${editInfo.value.effectEndDate}”？变更后有效期：${
            editInfo.value.effectDay
          }天，增加：${editInfo.value.effectDay - editInfo.value.effectDayLast}天`
        } else if (editInfo.value.type == 8) {
          if (editInfo.value.freezeEndDate) {
            tipVal = `请确认，是否将项目冻结期设置为“${editInfo.value.freezeStartDate} 至 ${editInfo.value.freezeEndDate}”，冻结天数：${editInfo.value.freezeDay}天？`
          } else {
            tipVal = `请确认，是否将项目冻结期设置为“${editInfo.value.freezeStartDate} 至 永久？`
          }
        }
        if (tipVal) {
          dt.ui.Modal.confirm({
            title: '确认',
            content: tipVal,
            onOk: () => {
              let params = {
                tenantId: editInfo.value.id,
                changeDescription: editInfo.value.changeDescription,
                changeType: editInfo.value.type,
                belongUserPhone: editInfo.value.belongUserPhone,
                belongUserName: editInfo.value.belongUserName,
                tenantName: editInfo.value.tenantName,
                companyId: editInfo.value.companyId,
                provinceCode: editInfo.value.peopleCity[0],
                cityCode: editInfo.value.peopleCity[1],
                effectStartDate: editInfo.value.effectStartDate,
                effectEndDate: editInfo.value.effectEndDate,

                freezeStartDate: editInfo.value.freezeStartDate,
                freezeEndDate: editInfo.value.freezeEndDate
              }
              apiMgr.changeTenantForWeb(params).then((res) => {
                emits('successful')
              })
            },
            onCancel: () => {
              dt.ui.Message.info('您取消了操作。')
            }
          })
        }
      }
    })
  }

  const cancelData = () => {
    editInfo.value = {
      tenantName: '',
      companyId: '',
      companyName: '',
      belongUserPhone: null,
      phoneVerify: null,
      belongUserName: '',
      peopleCity: [],
      cityName: '',
      cityCode: '',
      provinceCode: '',
      effectEndDate: null,
      effectStartDate: null,
      day: '',
      accountNumber: '',
      changeDescription: '',
      effectDay: '',
      effectSurplusDay: '',

      freezeStartDate: '',
      freezeEndDate: '',
      freezeDay: '',
      freezeEndDateAddEffectSurplusDay: '',
      freeTips: ''
    }
  }

  const hide = () => editRef.value.hide()
  const infoChangeList = ref([])
  const infoChangeList1 = ref([
    { key: '2', name: '变更项目名称' },
    { key: '3', name: '变更项目合同主体' },
    { key: '4', name: '变更项目所属人名称' },
    { key: '5', name: '变更项目所属人手机号' },
    { key: '6', name: '变更项目所属人城市' }
  ])
  const infoChangeList2 = ref([
    { key: '7', name: '有效期变更' },
    { key: '8', name: '有效期冻结' }
  ])

  const show = (val, val1) => {
    editInfo.value.tenantCode = val.tenantCode
    editInfo.value.tenantStatusName = val.tenantStatusName
    editInfo.value.tenantStatus = val.tenantStatus
    editInfo.value.tenantNameLast = val.tenantName
    editInfo.value.id = val.id
    editInfo.value.type = null
    if (val1 == 1) {
      editInfo.value.companyNameLast = val.companyName
      editInfo.value.belongUserNameLast = val.belongUserName
      editInfo.value.belongUserPhoneLast = val.belongUserPhone
      editInfo.value.cityLast = val.city
      infoChangeList.value = infoChangeList1.value
    } else {
      editInfo.value.effectStartDateLast = val.effectStartDate
      editInfo.value.effectEndDateLast = val.effectEndDate
      editInfo.value.effectDayLast = val.effectDay
      editInfo.value.effectSurplusDayLast = val.effectSurplusDay
      editInfo.value.freezeStartDate = val.freezeStartDate
      editInfo.value.freezeEndDate = val.freezeEndDate
      editInfo.value.freezeDay = val.freezeDay

      let newMoment = moment(editInfo.value.freezeEndDate, 'YYYY-MM-DD').add(
        editInfo.value.effectSurplusDayLast,
        'days'
      )
      editInfo.value.freezeEndDateAddEffectSurplusDay = editInfo.value.freezeEndDate
        ? newMoment.format('YYYY-MM-DD')
        : ''

      if (editInfo.value.tenantStatus == 3) {
        editInfo.value.effectStartDate = val.effectStartDate
      }

      if (editInfo.value.freezeStartDate && !editInfo.value.freezeEndDate) {
        editInfo.value.freeTips = '设置说明：如“冻结结束日期”未填写，则表示该项目永久冻结'
      } else if (editInfo.value.freezeStartDate && editInfo.value.freezeEndDate) {
        editInfo.value.freeTips = `该项目将冻结至${editInfo.value.freezeEndDate}，并于${editInfo.value.freezeEndDateAddEffectSurplusDay}起恢复`
      }
      infoChangeList.value = infoChangeList2.value
    }

    editRef.value.show()
  }
  const showModal = ref(false)
  defineExpose({
    show,
    hide
  })
</script>

<style lang="scss" scoped>
  .allBox {
    max-height: 80vh;
    overflow-y: auto;
    overflow-x: hidden;
  }
  .topBox {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    border: 1px #ccc solid;
    background: #f7f4f4;
    padding: 20px 20px;
    line-height: 30px;
    font-size: 16px;
  }
  .selBox {
    margin: 20px;
  }
</style>
